package com.firefly.app.biz.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: (le.qiao)
 * @e-mail: qiaolevip@gmail.com
 * @myblog: <a href="http://qiaolevip.iteye.com">http://qiaolevip.iteye.com</a>
 * @date: 2013-10-17
 * 
 */
public class FileOperate {

	/**
	 * 获得远程文件长度
	 * 
	 * @param siteUrl
	 * @return
	 */
	public static long getRemoteFileSize(String siteUrl) {
		int nFileLength = -1;
		try {
			URL url = new URL(siteUrl);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestProperty("User-Agent", "NetFox");
			int responseCode = httpConnection.getResponseCode();
			if (responseCode >= 400) {
				processErrorCode(responseCode);
				return -2; // -2 represent access is error
			}
			String sHeader;
			for (int i = 1;; i++) {
				sHeader = httpConnection.getHeaderFieldKey(i);
				if (sHeader != null) {
					if (sHeader.equals("Content-Length")) {
						nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
						break;
					}
				} else
					break;
			}
			httpConnection.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Utility.log("获取远程文件大小：" + nFileLength);
		return nFileLength;
	}

	/**
	 * 获得远程文件长度2
	 * 
	 * @param siteUrl
	 * @return
	 */
	public static long getRemoteFileSize2(String siteUrl) {
		int nFileLength = -1;
		try {
			HttpURLConnection httpConnection = (HttpURLConnection) (new URL(siteUrl)).openConnection();
			int responseCode = httpConnection.getResponseCode();
			if (responseCode >= 400) {
				processErrorCode(responseCode);
				return -2; // -2 represent access is error
			}
			nFileLength = httpConnection.getContentLength();
			httpConnection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Utility.log("获取远程文件大下：" + nFileLength);
		return nFileLength;
	}

	/**
	 * 断点下载远程文件
	 * 
	 * @param nStartPos
	 * @param nEndPos
	 * @param sURL
	 */
	public static void downloadRemoteFileContent(int nStartPos, int nEndPos, String sURL) {
		while (nStartPos < nEndPos) {
			try {
				FileAccessI fileAccessI = new FileAccessI();
				URL url = new URL(sURL);
				HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
				httpConnection.setRequestProperty("User-Agent", "NetFox");
				String sProperty = "bytes=" + nStartPos + "-";
				httpConnection.setRequestProperty("RANGE", sProperty);
				Utility.log(sProperty);
				int contentLength = httpConnection.getContentLength();
				if (contentLength > 1400) {
					InputStream input = httpConnection.getInputStream();
					// logResponseHead(httpConnection);
					byte[] b = new byte[1024];
					int nRead;
					while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos) {
						nStartPos += fileAccessI.write(b, 0, nRead);
					}
					input.close();
				}
//				fileAccessI.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static void processErrorCode(int nErrorCode) {
		Utility.log("Error Code : " + nErrorCode);
	}

	// 重命名文件
	public static void renameFile(String fileName) {
		File oldTempFile = new File(fileName);
		
		if (oldTempFile.exists()) {
			
			System.gc();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			File newSaveFile = new File(fileName.substring(0, fileName.lastIndexOf(".")));
			boolean result =  oldTempFile.renameTo(newSaveFile);
			
			Utility.log("重命名后的文件：" + newSaveFile.getAbsolutePath() + "，重命名结果：" + (result ? "成功" : "失败"));

			File tempFileInfo = new File(oldTempFile + ".info");
			delTempFile(tempFileInfo);
//			boolean result = true;
//			
//
//			copyfile(fileName, newSaveFile.getAbsolutePath());
//			
////			delTempFile(newSaveFile);
//
//			
//

//			delTempFile(tempFileInfo);
//			delTempFile(oldTempFile);
			
		}
	}

	/**
	 * 复制文件
	 * 
	 * @param srFile
	 * @param dtFile
	 */
	public static void copyfile(String srFile, String dtFile) {
		try {
			File f1 = new File(srFile);
			File f2 = new File(dtFile);
			InputStream in = new FileInputStream(f1);

			// For Append the file.
			// OutputStream out = new FileOutputStream(f2,true);

			// For Overwrite the file.
			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			Utility.log("复制文件：" + f2.getAbsolutePath());
		} catch (FileNotFoundException ex) {
			System.out.println(ex.getMessage() + " in the specified directory.");
			System.exit(0);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	// 删除临时文件
	public static void delTempFile(File file) {
		if (file.exists()) {
			System.gc();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			boolean result = file.delete();

			Utility.log("删除文件：" + file.getAbsolutePath() + "，删除结果：" + (result ? "成功" : "失败"));
		}
	}

	// 删除错误文件
	public static void delErrorFile(File file) {
		delTempFile(file);
		file = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".")));
		delTempFile(file);
	}
}
